local skynet = require "skynet"
require "skynet.manager"
local identity, kind = ...

local base = require "util.base"
local class = require "util.class"
local consumermgr = class(base)

function consumermgr:ctor()
	self.running = true
end

function consumermgr:task()
	while true do
		local answer, goods = skynet.call(".store", "lua", "have_goods") 
		if answer then
			skynet.error(identity, "consumer see:", goods)
			if string.sub(goods,3) % kind == 0 then
				local result = skynet.call(".store", "lua", "consume", goods)
				if result then
					skynet.error(identity, "consumer get:", goods)
				else	
					skynet.error(identity, "consumer get fail:", goods)
				end
			else
				skynet.error(identity, "consumer don\"t want:", goods)
			end
			skynet.sleep(100)
		else
			skynet.error("consumer:", identity, "stoptask")
			self.running = false
			break
		end
	end
end

function consumermgr:restart()
	if not self.running then
		self.running = true
		self:task()
	end
end

skynet.start(function()	
	skynet.send(".store", "lua", "chandler", skynet.self())
	local mgr = consumermgr.new()
	
	skynet.dispatch("lua", function(session, address, sign, ...)
		mgr:run(sign, ...)	
	end)
	
	skynet.fork(function() mgr:task() end)
end)